package integration.data.task.api.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import integration.data.task.api.transformation.impl.TransformerExecution;
import integration.data.task.api.transformation.impl.TransformerExecutionParas;
import integration.data.task.api.transformation.impl.TransformerInfo;
import integration.data.task.api.transformation.impl.TransformerRegistry;
import integration.modle.exception.IntegrationValidException;
import integration.utils.trace.LogUtils;
import io.github.bigbird0101.datatransfer.model.config.TransformerConfig;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 转换函数utils
 */
@Slf4j
public class TransformerUtil {

    public static List<TransformerExecution> buildTransformerInfo(List<TransformerConfig> transformerConfigList) {

        if (transformerConfigList == null || transformerConfigList.isEmpty()) {
            return null;
        }

        List<TransformerExecution> result = new ArrayList<TransformerExecution>(4);

        int i = 0;
        for (TransformerConfig transformerConfig : transformerConfigList) {
            String functionName = transformerConfig.getType();
            List<Map<String, Object>> paramList = transformerConfig.getParam();

            if (StrUtil.isBlank(functionName)) {
                LogUtils.warn(log, "转换函数配置函数名称为空：{}", JSONUtil.toJsonStr(transformerConfig));
                throw new IntegrationValidException("转换函数配置缺少函数名称");
            }
            if (paramList == null || paramList.isEmpty()) {
                LogUtils.warn(log, "转换函数配置错误：{}", JSONUtil.toJsonStr(transformerConfig));
                throw new IntegrationValidException("转换函数配置缺少函数参数");
            }

            TransformerInfo transformerInfo = TransformerRegistry.getTransformer(functionName);

            if (transformerInfo == null) {
                throw new IntegrationValidException(String.format("不支持的转换函数：%s", functionName));
            }

            for (Map<String, Object> param : paramList) {

                /**
                 * 具体的UDF对应一个paras
                 */
                TransformerExecutionParas transformerExecutionParas = new TransformerExecutionParas();
                transformerExecutionParas.setCode(functionName);
                transformerExecutionParas.setParas(param);
                transformerExecutionParas.setColumnIndex((Integer) param.get("column"));
                TransformerExecution transformerExecution = new TransformerExecution(transformerInfo, transformerExecutionParas);
                result.add(transformerExecution);
                i++;
                LogUtils.info(log, String.format(" %s of transformer init success. name=%s, parameter = %s"
                        , i, transformerInfo.getTransformer().getTransformerName(), param));
            }
        }
        return result;
    }

}
